import json
import re
import uuid

from rest_framework import serializers, status
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response

from apps.common.common_func import checkIdcard, value_is_in_arr
from apps.opoc.models import Opoc_InspectionRecord, Opoc_InspectionPhoto, Opoc_InspectionPhoto_temp
from extensions.exceptions import ValidationError
from extensions.serializers import *
from apps.opoc.models import *


class MobileOpoc_Records_ListSerializer(BaseSerializer):
    # inspectionrecord_count = serializers.IntegerField()  # 添加一个IntegerField来处理inspectionrecord_count属性
    inspectionrecord_count = serializers.SerializerMethodField()
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    class Meta:
        model = Opoc_Records
        fields =  ['id', 'company','name','sfz_number','phone','company_name','slug','inspectionrecord_count']


    def get_inspectionrecord_count(self, obj):
        return getattr(obj, 'inspectionrecord_count', None)


class DesktopOpoc_Records_ListSerializer(BaseSerializer):
    # inspectionrecord_count = serializers.IntegerField()  # 添加一个IntegerField来处理inspectionrecord_count属性
    inspectionrecord_count = serializers.SerializerMethodField()
    labor_service_unit_name = CharField(source='labor_service_unit.name', read_only=True, label='公司')
    company_name = CharField(source='company.name',  read_only=True, label='公司')

    class Meta:
        model = Opoc_Records
        fields =  "__all__"

    def get_inspectionrecord_count(self, obj):
        return getattr(obj, 'inspectionrecord_count', None)


class Opoc_RecordsSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    labor_service_unit_name = CharField(source='labor_service_unit.name',  read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    # next_checker_name = CharField(source='next_checker.name',  read_only=True, label='下一步审核人')

    class Opoc_Certificate_ImgsSerializer(BaseSerializer):
        class Meta:
            model = Opoc_Certificate_Imgs
            fields = ['id', 'file','name','type']

    climb_high_img_item = Opoc_Certificate_ImgsSerializer(source='climb_high_img', read_only=True,label='登高证')
    electrician_img_item = Opoc_Certificate_ImgsSerializer(source='electrician_img', read_only=True,label='电工证')
    safety_officer_img_item = Opoc_Certificate_ImgsSerializer(source='safety_officer_img', read_only=True,label='安全员证')
    other_person_img_item = Opoc_Certificate_ImgsSerializer(source='other_person_img', read_only=True,label='其它证')

    class Common_PdfsSerializer(BaseSerializer):
        class Meta:
            model = Common_Pdfs
            fields = "__all__"


    construction_contract_pdf_item = Common_PdfsSerializer(source='construction_contract_pdf', read_only=True, label='施工合同')
    insurance_pdf_item = Common_PdfsSerializer(source='insurance_pdf', read_only=True, label='保险')
    safety_responsibility_pdf_item = Common_PdfsSerializer(source='safety_responsibility_pdf', read_only=True, label='安全责任书')
    safety_education_pdf_item = Common_PdfsSerializer(source='safety_education_pdf', read_only=True, label='安全教育')
    safety_disclosure_pdf_item = Common_PdfsSerializer(source='safety_disclosure_pdf', read_only=True, label='安全交底')
    service_order_pdf_item = Common_PdfsSerializer(source='service_order_pdf', read_only=True, many=True,label='服务订单')
    task_dispatch_pdf_item = Common_PdfsSerializer(source='task_dispatch_pdf', read_only=True, many=True,label='任务单')
    # labor_service_unit_items = Labor_service_unitsSerializer(source='labor_service_unit', read_only=True,many=True,label='任务单')
    # labor_service_unit_items = Labor_service_unitsSerializer(source='labor_service_unit', many=True,label='任务单')
    # class OpocChecksSerializer(BaseSerializer):
    #     check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
    #     class Meta:
    #         model = OpocCheck
    #         fields = ['id', 'opoc','check_user','check_user_name','opinion','is_agree','add_time']
    #
    # opoc_checks_items = OpocChecksSerializer(
    #     source='check_records', many=True, read_only=True, label='审核记录')

    class Meta:
        model = Opoc_Records
        read_only_fields = [
                            'id',
                            'company_name',
                            # 'opoc_checks_items',
                            'climb_high_img_item',
                            'labor_service_unit_name',
                            # 'next_checker_name',
                            'filled_by_name',
                            'slug',
                            'electrician_img_item','safety_officer_img_item','other_person_img_item',
                            'construction_contract_pdf_item','insurance_pdf_item','safety_responsibility_pdf_item',
                            'safety_education_pdf_item','safety_disclosure_pdf_item','service_order_pdf_item',
                            'task_dispatch_pdf_item',
                            # 'labor_service_unit',
                            'add_time',
                            ]
        fields = '__all__'

    # def create(self, validated_data):
    #     print('validated_data1:', validated_data)
    #     labor_service_units_data  = validated_data.pop('labor_service_unit', [])
    #     print('labor_service_units:',labor_service_units_data)
    #     opoc_record = Opoc_Records.objects.create(**validated_data)
    #     opoc_record.save()
    #     print('opoc_record:', opoc_record)
    #     for labor_service_unit in labor_service_units_data:
    #         opoc_record.labor_service_unit.add(labor_service_unit)
    #     return opoc_record

    def validate_id_number(self, value):
        res =checkIdcard(value)
        if res!=True:
            raise ValidationError(value+"身份证号码格式不对")
        return value

    def validate_phone(self, value):
        res = re.match(r'1[3,4,5,6,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,6,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value
    #
    # def validate(self, attrs):
    #     certificate_holding = attrs.get('certificate_holding')
    #     climb_high_img =attrs.get('climb_high_img')
    #     electrician_img =attrs.get('electrician_img')
    #     safety_officer_img =attrs.get('safety_officer_img')
    #     other_person_img =attrs.get('other_person_img')
    #     if 1 in certificate_holding:
    #         if not climb_high_img:
    #             raise ValidationError('请上传登高证')
    #     if 2 in certificate_holding:
    #         if not electrician_img:
    #             raise ValidationError('请上传电工证')
    #     if 3 in certificate_holding:
    #         if not safety_officer_img:
    #             raise ValidationError('请上传安全员证')
    #     if 4 in certificate_holding:
    #         if not other_person_img:
    #             raise ValidationError('请上传其它证')
    #     return attrs

    def create(self, validated_data):
        service_order_pdfs = validated_data.pop('service_order_pdf', [])
        task_dispatch_pdfs = validated_data.pop('task_dispatch_pdf', [])
        instance = Opoc_Records(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.slug = instance.generate_slug()
        instance.service_order_pdf.set(service_order_pdfs)
        instance.task_dispatch_pdf.set(task_dispatch_pdfs)
        instance.save()

        return instance
    #
    def update(self, instance, validated_data):
        service_order_pdfs = validated_data.pop('service_order_pdf', [])
        task_dispatch_pdfs = validated_data.pop('task_dispatch_pdf', [])

        instance = super().update(instance, validated_data)
        instance.service_order_pdf.set(service_order_pdfs)
        instance.task_dispatch_pdf.set(task_dispatch_pdfs)

        return instance
        # return super().update(instance, validated_data)


class Opoc_RecordsImportSerializer(BaseSerializer):
    date_format = '%Y-%m-%d'
    # class Opoc_Labor_service_unitsSerializer(BaseSerializer):
    #     class Meta:
    #         model = Labor_service_unit
    #         read_only_fields = ['__all__']
    name = CharField(label='姓名，填真实姓名')
    sfz_number = CharField(label='身份证号码(必填唯一)')
    phone = CharField(required=False, label='联系电话，填手机号')
    status = IntegerField(required=False, label='人员状态，数字：1=参工2=待工-1=离职')
    ascription = JSONField(required=False, label='归属劳务单位，格式：[1,2]：1=比选+短名单2=综合劳务3=招募+二次甄选')
    labor_service_unit = JSONField(required=False,label='劳务单位unit_id，格式：数字，填劳务单位对应的unit_id')
    team_attribute = JSONField(required=False, label='队伍属性，格式：[1,2]：:1=架子队+短名单2=市州工程队3=区县工程队4=劳务单位施工队')
    certificate_holding = JSONField(required=False, label='持证情况，格式：[1,2],1=登高证2=电工证3=安全员证4=其它证')
    contract_signing_begin_date = DateTimeField(input_formats=[date_format ],required=False, label='与劳务单位合同签订日期，格式：年-月-日，如：\'2022-02-21(前面要加半角单引号\'，下同)')
    contract_signing_end_date = DateTimeField(input_formats=[date_format ],required=False, label='与劳务单位合同截止日期，格式：年-月-日，如：2022-08-21')
    insurance_limit = FloatField(required=False, label='保险额度（万元），数字:如100')
    insurance_effective_date = DateTimeField(input_formats=[date_format ],required=False, label='保险购买生效日，格式：年-月-日，如：2022-02-21')
    insurance_invalid_date = DateTimeField(input_formats=[date_format ],required=False, label='保险购买失效日，格式：年-月-日，如：2022-08-21')
    is_safety_responsibility = BooleanField(required=False, label='与劳务单位安全责任书签订，数字：1=已签订,0=未签订')
    project_name = CharField(required=False, label='实施项目名称')
    is_safety_education = BooleanField(required=False, label='上岗前的安全教育培训及考核，数字：1=已培训考核合格,0=未组织培训考核')
    is_monthly_safety_education = BooleanField(required=False, label='月度安全教育培训，数字：1=已组织,0=未组织')
    is_service_order = BooleanField(required=False, label='服务订单工单派发，数字：1=已派发,0=未派发')
    is_task_dispatch = BooleanField(required=False, label='任务单派发，数字：1=已派发,0=未派发')
    is_safety_disclosure = BooleanField(required=False, label='项目启动安全技术交底，数字：1=已组织,0=未组织')
    other_conditions = CharField(required=False, label='其他需要说明的情况')
    construction_contract_pdf = CharField(required=False, label='合同附件pdf_id，数字，填合同附件对应的pdf_id')
    insurance_pdf = CharField(required=False, label='保险附件pdf_id，数字，填保险附件对应的pdf_id')
    safety_responsibility_pdf = CharField(required=False, label='安全责任书附件pdf_id，数字，填安全责任书附件对应的pdf_id')
    safety_education_pdf = CharField(required=False, label='岗前教育培训附件pdf_id，数字，填岗前教育培训附件对应的pdf_id')
    safety_disclosure_pdf = CharField(required=False, label='项目启动前的安全技术交底附件pdf_id，数字，填项目启动前的安全技术交底附件对应的pdf_id')
    service_order_pdf = JSONField(required=False, label='服务订单工单附件pdf_id，格式：[id1,id2]')
    task_dispatch_pdf = JSONField(required=False, label='任务单附件pdf_id，数字，格式：[id1,id2]')
    climb_high_img = CharField(required=False, label='登高证附件img_id，字符串，填登高证附件对应的img_id')
    electrician_img = CharField(required=False, label='电工证附件img_id，字符串，填电工证附件对应的img_id')
    safety_officer_img = CharField(required=False, label='安全员证附件img_id，字符串，填安全员证附件对应的img_id')
    other_person_img = CharField(required=False, label='其它证附件img_id，字符串，填其它证附件对应的img_id')
    class Meta:
        model = Opoc_Records

        fields = [
            'name','sfz_number','phone','status',
            'ascription',
            'labor_service_unit',
            'team_attribute',
            'certificate_holding',
            'contract_signing_begin_date',
            'contract_signing_end_date',
            'insurance_limit',
            'insurance_effective_date',
            'insurance_invalid_date',
            'is_safety_responsibility','project_name','is_safety_education',
            'is_monthly_safety_education','is_service_order','is_task_dispatch','is_safety_disclosure',
            'other_conditions',
            'construction_contract_pdf',
            'insurance_pdf','safety_responsibility_pdf',
            'safety_education_pdf','safety_disclosure_pdf','service_order_pdf','task_dispatch_pdf',
            'climb_high_img','electrician_img','safety_officer_img','other_person_img',
        ]


    def to_representation(self, instance):
        """将日期格式化为字符串"""
        data = super().to_representation(instance)
        for field_name, field in self.fields.items():
            if isinstance(field, serializers.DateTimeField):
                value = data.get(field_name)
                if value:
                    data[field_name] = value.strftime(self.date_format)
        return data

    def to_internal_value(self, data):
        # Convert the 'ascription' field from string to Python object
        ascription_str = data.get('ascription')
        labor_service_unit_str = data.get('labor_service_unit')
        team_attribute_str = data.get('team_attribute')
        certificate_holding_str = data.get('certificate_holding')
        service_order_pdf_str = data.get('service_order_pdf')
        task_dispatch_pdf_str = data.get('task_dispatch_pdf')
        if ascription_str:
            data['ascription'] = json.loads(ascription_str)
        if labor_service_unit_str:
            data['labor_service_unit'] = json.loads(labor_service_unit_str)
        if team_attribute_str:
            data['team_attribute'] = json.loads(team_attribute_str)
        if certificate_holding_str:
            data['certificate_holding'] = json.loads(certificate_holding_str)
        if service_order_pdf_str:
            data['service_order_pdf'] = json.loads(service_order_pdf_str)
        if task_dispatch_pdf_str:
            data['task_dispatch_pdf'] = json.loads(task_dispatch_pdf_str)
        return super().to_internal_value(data)

    def validate_status(self, value):
        if value_is_in_arr(value,[0,1,-1])==False:
            raise ValidationError('人员状态' + str(value) + '不在[0,1,-1]范围内')
        return value

    def validate_id_number(self, value):
        res =checkIdcard(value)
        if res!=True:
            raise ValidationError(value+"身份证号码格式不对")
        return value

    def validate_phone(self, value):
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value


class Opoc_Certificate_ImgsSerializer(BaseSerializer):
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    class Meta:
        model = Opoc_Certificate_Imgs
        read_only_fields = ['id', 'name','type','company_name',
                            'filled_by','filled_by_name','add_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['type'] = self.request.data['type']
        validated_data['filled_by'] = self.user
        validated_data['company'] = self.user.company
        return super().create(validated_data)


class Opoc_Common_PdfsSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Common_Pdfs
        read_only_fields = ['id', 'company','company_name','name','type',
                            'filled_by','filled_by_name','add_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['company'] = self.user.company
        validated_data['type'] = self.request.data['type']
        validated_data['filled_by'] = self.user
        return super().create(validated_data)


class Opoc_InspectionPhotosSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Opoc_InspectionPhoto
        read_only_fields = ['id', 'company','company_name','name',
                            'filled_by','filled_by_name','add_time']
        fields = ['opoc_inspectionRecord','file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['company'] = self.user.company
        validated_data['filled_by'] = self.user
        return super().create(validated_data)


class Opoc_InspectionPhotosTempSerializer(BaseSerializer):
    class Meta:
        model = Opoc_InspectionPhoto_temp
        read_only_fields = ['id']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        return super().create(validated_data)


class Opoc_InspectionRecordsSerializer(BaseSerializer):
    company = CharField(source='opoc_record.company', read_only=True, label='公司')
    company_name = CharField(source='opoc_record.company.name', read_only=True, label='公司名')
    opoc_record_name = CharField(source='opoc_record.name',  read_only=True, label='被检查人')
    opoc_record_sfz_number = CharField(source='opoc_record.sfz_number',  read_only=True, label='被检查人身份证号码')
    opoc_record_phone = CharField(source='opoc_record.phone',  read_only=True, label='被检查人电话')
    inspector_name = CharField(source='inspector.name',  read_only=True, label='检查人')
    opoc_InspectionPhotos=Opoc_InspectionPhotosSerializer(source='Opoc_InspectionPhoto', many=True, read_only=True, label='检查照片')

    class Meta:
        model = Opoc_InspectionRecord
        read_only_fields = ['id', 'company','company_name','inspector_name','opoc_record_sfz_number','opoc_record_phone','opoc_record_name','created_at',
                            'opoc_InspectionPhotos'
                            ]
        fields = [
            'inspection_location',
            'content',
            'problem',
            'opoc_record',
            'latitude',
            'longitude',
            'inspector',
            'remarks',
            *read_only_fields
        ]

    def create(self, validated_data):
        validated_data['inspector'] = self.user
        record = super().create(validated_data)
        # 获取临时图片的 ID 列表
        temp_photo_ids = self.context['request'].data.get('temp_photo_ids', [])
        if not isinstance(temp_photo_ids, list):
            raise serializers.ValidationError("temp_photo_ids must be a list.")

        for temp_photo_id in temp_photo_ids:
            if temp_photo_id:
                # 根据临时图片的 ID 找到相应的图片
                temp_photo = get_object_or_404(Opoc_InspectionPhoto_temp, id=temp_photo_id)

                # 创建一个新的 Opoc_InspectionPhoto，将图片和新的检查记录关联起来
                Opoc_InspectionPhoto.objects.create(
                    opoc_inspectionRecord=record,
                    file=temp_photo.file,
                    name=temp_photo.name,
                    company = self.user.company,
                    filled_by = self.user
                    # 其他字段
                )
                # 删除临时图片的记录
                temp_photo.delete()

        return record



class Opoc_Labor_service_unitsSerializer(BaseSerializer):
    slug = serializers.SlugField(default=serializers.CreateOnlyDefault(''))
    # id = serializers.SerializerMethodField()
    company_name = CharField(source='company.name', read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Labor_service_unit
        read_only_fields = ['id','slug','company_name',
                            'filled_by_name','add_time']
        fields = '__all__'

    def get_id(self, instance):
        return str(uuid.UUID(instance.id)).upper()

    # def create(self, validated_data):
    #     instance = super().create(validated_data)
    #     instance.id = uuid.UUID(instance.id).hex
    #     instance.save()
    #     return instance

    # def update(self, instance, validated_data):
    #     instance = super().update(instance, validated_data)
    #     instance.id = uuid.UUID(instance.id).hex
    #     instance.save()
    #     return instance
    # def get_id(self, obj):
    #     return str(obj.id).replace('-', '')



class Labor_service_unitImportExportSerializer(BaseSerializer):
    name = CharField(label='劳务单位名称(必填唯一)')
    class Meta:
        model = Labor_service_unit
        fields = ['name']




__all__ = [
    'MobileOpoc_Records_ListSerializer',
    'DesktopOpoc_Records_ListSerializer',
    'Opoc_RecordsSerializer',
    'Opoc_Common_PdfsSerializer',
    'Opoc_Labor_service_unitsSerializer',
    'Labor_service_unitImportExportSerializer',
    'Opoc_Certificate_ImgsSerializer',
    'Opoc_RecordsImportSerializer',
]